package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/login")
    @ResponseBody
    public JsonResult login(String username, String password, HttpSession session){

        if (username==null||username.trim().equals("")){
            return new JsonResult("账号不能为空",false);
        }else if (password==null||password.trim().equals("")){
            return new JsonResult("请输入密码",false);
        }else {
            try {

                Employee employee = employeeService.login(username,password);



                if (!employee.isAdmin()){
                    //优化功能  在此处根据员工id  查询权限 避免每次操作都需要从数据库中查询权限
                    //如果不是管理员 则需要查询权限
                    List<String> expressions = permissionService.selectByEmployeeId(employee.getId());

                    UserContext.setExpression(expressions);

                }

                UserContext.setCurrentUser(employee);
                return new JsonResult();
            }catch (Exception e){
                return new JsonResult(e.getMessage(),false);
            }
        }

    }



    @RequestMapping("/logout")
    public String logout(HttpSession session){

        session.invalidate();

        return "redirect:/login.html";

    }






}
